#!/usr/bin/env python3
"""
智慧医院资源调度系统测试脚本
"""

import requests
import json
import time
from datetime import datetime, timedelta

# 配置
BASE_URL = 'http://localhost:5000'
API_URL = f'{BASE_URL}/api'

def test_api_connection():
    """测试API连接"""
    print("🔍 测试API连接...")
    try:
        response = requests.get(f'{API_URL}/auth/profile', timeout=5)
        print(f"  API响应状态: {response.status_code}")
        return True
    except requests.exceptions.ConnectionError:
        print("  ❌ 无法连接到API服务器")
        return False
    except Exception as e:
        print(f"  ❌ 连接测试失败: {e}")
        return False

def test_user_registration():
    """测试用户注册"""
    print("👤 测试用户注册...")
    
    user_data = {
        'username': 'test_user',
        'email': 'test@example.com',
        'password': 'test123',
        'role': 'patient',
        'phone': '13800138000'
    }
    
    try:
        response = requests.post(f'{API_URL}/auth/register', json=user_data)
        if response.status_code == 201:
            print("  ✅ 用户注册成功")
            return True
        else:
            print(f"  ❌ 用户注册失败: {response.text}")
            return False
    except Exception as e:
        print(f"  ❌ 注册测试失败: {e}")
        return False

def test_user_login():
    """测试用户登录"""
    print("🔐 测试用户登录...")
    
    login_data = {
        'username': 'admin',
        'password': 'admin123'
    }
    
    try:
        response = requests.post(f'{API_URL}/auth/login', json=login_data)
        if response.status_code == 200:
            data = response.json()
            token = data.get('access_token')
            print("  ✅ 用户登录成功")
            return token
        else:
            print(f"  ❌ 用户登录失败: {response.text}")
            return None
    except Exception as e:
        print(f"  ❌ 登录测试失败: {e}")
        return None

def test_appointment_creation(token):
    """测试预约创建"""
    print("📅 测试预约创建...")
    
    headers = {'Authorization': f'Bearer {token}'}
    appointment_data = {
        'department_id': 1,
        'appointment_type': 'consultation',
        'scheduled_time': (datetime.now() + timedelta(days=1)).isoformat(),
        'duration': 30,
        'priority': 1,
        'notes': '测试预约'
    }
    
    try:
        response = requests.post(f'{API_URL}/appointments', json=appointment_data, headers=headers)
        if response.status_code == 201:
            data = response.json()
            print(f"  ✅ 预约创建成功，ID: {data.get('appointment_id')}")
            return data.get('appointment_id')
        else:
            print(f"  ❌ 预约创建失败: {response.text}")
            return None
    except Exception as e:
        print(f"  ❌ 预约创建测试失败: {e}")
        return None

def test_scheduling_optimization(token):
    """测试调度优化"""
    print("⚙️ 测试调度优化...")
    
    headers = {'Authorization': f'Bearer {token}'}
    scheduling_data = {
        'algorithm': 'hybrid',
        'department_id': 1
    }
    
    try:
        response = requests.post(f'{API_URL}/scheduling/optimize', json=scheduling_data, headers=headers)
        if response.status_code == 200:
            data = response.json()
            print(f"  ✅ 调度优化成功，算法: {data.get('algorithm')}")
            print(f"  📊 资源利用率: {data.get('objectives', {}).get('resource_utilization', 0):.2f}%")
            print(f"  ⏱️ 平均等待时间: {data.get('objectives', {}).get('patient_wait_time', 0):.2f}分钟")
            return True
        else:
            print(f"  ❌ 调度优化失败: {response.text}")
            return False
    except Exception as e:
        print(f"  ❌ 调度优化测试失败: {e}")
        return False

def test_resource_management(token):
    """测试资源管理"""
    print("🏥 测试资源管理...")
    
    headers = {'Authorization': f'Bearer {token}'}
    
    try:
        # 获取资源列表
        response = requests.get(f'{API_URL}/resources', headers=headers)
        if response.status_code == 200:
            resources = response.json()
            print(f"  ✅ 获取资源列表成功，共{len(resources)}个资源")
            
            # 获取资源利用率
            response = requests.get(f'{API_URL}/resources/utilization', headers=headers)
            if response.status_code == 200:
                utilizations = response.json()
                print(f"  📊 资源利用率数据: {len(utilizations)}条记录")
                return True
            else:
                print(f"  ❌ 获取资源利用率失败: {response.text}")
                return False
        else:
            print(f"  ❌ 获取资源列表失败: {response.text}")
            return False
    except Exception as e:
        print(f"  ❌ 资源管理测试失败: {e}")
        return False

def test_metrics_api(token):
    """测试指标API"""
    print("📈 测试系统指标...")
    
    headers = {'Authorization': f'Bearer {token}'}
    
    try:
        response = requests.get(f'{API_URL}/metrics/overview', headers=headers)
        if response.status_code == 200:
            data = response.json()
            print("  ✅ 系统指标获取成功")
            print(f"  📊 总预约数: {data.get('appointments', {}).get('total', 0)}")
            print(f"  🏥 总资源数: {data.get('resources', {}).get('total', 0)}")
            print(f"  📈 资源利用率: {data.get('resources', {}).get('utilization_rate', 0):.2f}%")
            return True
        else:
            print(f"  ❌ 获取系统指标失败: {response.text}")
            return False
    except Exception as e:
        print(f"  ❌ 系统指标测试失败: {e}")
        return False

def run_performance_test():
    """运行性能测试"""
    print("🚀 运行性能测试...")
    
    # 测试并发请求
    import concurrent.futures
    import threading
    
    def make_request():
        try:
            response = requests.get(f'{API_URL}/metrics/overview', timeout=10)
            return response.status_code == 200
        except:
            return False
    
    # 并发测试
    start_time = time.time()
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        futures = [executor.submit(make_request) for _ in range(50)]
        results = [future.result() for future in concurrent.futures.as_completed(futures)]
    
    end_time = time.time()
    success_count = sum(results)
    
    print(f"  📊 并发测试结果:")
    print(f"    - 总请求数: 50")
    print(f"    - 成功请求数: {success_count}")
    print(f"    - 成功率: {success_count/50*100:.1f}%")
    print(f"    - 总耗时: {end_time - start_time:.2f}秒")
    print(f"    - 平均响应时间: {(end_time - start_time)/50:.3f}秒")

def main():
    """主测试函数"""
    print("🧪 智慧医院资源调度系统测试")
    print("=" * 50)
    
    # 测试API连接
    if not test_api_connection():
        print("❌ API连接失败，请确保服务器正在运行")
        return
    
    # 测试用户注册
    test_user_registration()
    
    # 测试用户登录
    token = test_user_login()
    if not token:
        print("❌ 登录失败，无法继续测试")
        return
    
    # 测试预约创建
    appointment_id = test_appointment_creation(token)
    
    # 测试调度优化
    test_scheduling_optimization(token)
    
    # 测试资源管理
    test_resource_management(token)
    
    # 测试系统指标
    test_metrics_api(token)
    
    # 运行性能测试
    run_performance_test()
    
    print("\n✅ 所有测试完成！")
    print("🎉 系统运行正常，可以开始使用")

if __name__ == '__main__':
    main()
